package com.xc.sys.service;

import com.google.common.collect.Lists;
import com.xc.common.object.PageInfo;
import com.xc.common.tool.BeanAid;
import com.xc.common.tool.Helper;
import com.xc.db.tables.BaseCodeNumber;
import com.xc.db.tables.records.BaseCodeNumberRecord;
import com.xc.sys.entity.BaseCodeNumberEntity;
import com.xc.sys.entity.SysUserEntity;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SelectField;
import org.jooq.SelectForUpdateStep;
import org.jooq.SelectSeekStepN;
import org.jooq.SortField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BaseCodeNumberService {
	@Autowired
	private DSLContext dsl;
	private BaseCodeNumber BASECODENUMBER = BaseCodeNumber.BASE_CODE_NUMBER.as("BASECODENUMBER");

	public Result<Record> select(Condition whr, PageInfo<BaseCodeNumberEntity> pageInfo, SortField<?>... orderby) {
		SelectSeekStepN<Record> seek = this.dsl.select(new SelectField[0]).from(this.BASECODENUMBER)
				.where(new Condition[] { whr }).orderBy(orderby);
		Result<Record> result = null;
		if (pageInfo != null) {
			SelectForUpdateStep<Record> su = seek.limit(pageInfo.getLimit().intValue()).offset(pageInfo.getBeginNum());
			result = su.fetch();
		} else {
			result = seek.fetch();
		}
		if (pageInfo != null) {
			pageInfo.setResult(result);
			pageInfo.setList(result.into(BaseCodeNumberEntity.class));
		}
		return result;
	}

	public List<BaseCodeNumberEntity> select(Condition whr, SortField<?>... orderby) {
		Result<Record> result = dsl.select(new SelectField[0]).from(BASECODENUMBER).where(new Condition[] { whr }).orderBy(orderby).fetch();
		List<BaseCodeNumberEntity> list = Lists.newArrayList();
		if (result.size() > 0) {
			list = result.into(BaseCodeNumberEntity.class);
		}
		return list;
	}

	public Long count(Condition cond) {
		Long count = null;
		count = (Long) this.dsl.selectCount().from(this.BASECODENUMBER).where(new Condition[] { cond })
				.fetchOneInto(Long.class);
		return count;
	}

	public Record getRecordById(String id) {
		Record record = this.dsl.select(new SelectField[0]).from(this.BASECODENUMBER)
				.where(new Condition[] { this.BASECODENUMBER.ID.eq(id) }).fetchOne();
		return record;
	}

	public BaseCodeNumberEntity getEntityById(String id) {
		Record r = getRecordById(id);
		BaseCodeNumberEntity entity = null;
		if(r!=null) {
			entity = r.into(BaseCodeNumberEntity.class);
		}
		return entity;
	}

	public String update(BaseCodeNumberEntity entity) {
		BaseCodeNumberRecord record = new BaseCodeNumberRecord();
		record.from(entity);
		this.dsl.executeUpdate(record);
		return entity.getId();
	}

	public void update(Record record) {
		BaseCodeNumberRecord sysNaviRecord = new BaseCodeNumberRecord();
		sysNaviRecord.from(record);
		this.dsl.executeUpdate(sysNaviRecord);
	}

	public String insert(BaseCodeNumberEntity entity) {
		BaseCodeNumberRecord record = new BaseCodeNumberRecord();
		String id = entity.getId();
		if(StringUtils.isEmpty(entity.getId())) {
			id  = UUID.randomUUID().toString();
			entity.setId(id);
		}
		record.from(entity);
		this.dsl.executeInsert(record);
		return id;
	}

	public String save(BaseCodeNumberEntity entity) {
		if (StringUtils.isEmpty(entity.getId())) {
			return insert(entity);
		}
		return update(entity);
	}

	public void deleteById(String id) {
		dsl.delete(this.BASECODENUMBER).where(new Condition[] { BASECODENUMBER.ID.eq(id) }).execute();
	}
	public void deleteAll() {
		dsl.delete(this.BASECODENUMBER).execute();
	}
	@Transactional
	public static String genCode(String type,Integer length,HttpServletRequest request) {
		SysUserEntity me = Helper.getMe(request);
		String code = genCode(type, length);
		return code;
	}
	@Transactional
	public static String genCode(String type,Integer length) {
		BaseCodeNumber BASECODENUMBER = BaseCodeNumber.BASE_CODE_NUMBER.as("BASECODENUMBER");
		Condition conditions = BASECODENUMBER.TYPE.eq(type);//.and(BASECODENUMBER.ORG_ID.eq(org.getId()));
		BaseCodeNumberService baseCodeNumberService = BeanAid.getBean(BaseCodeNumberService.class);
		List<BaseCodeNumberEntity> codeList = baseCodeNumberService.select(conditions);
		String prefix = "";
		Long num = 0l;
		String code = "";
		if(codeList.size()==1) {
			BaseCodeNumberEntity baseCodeNumberEntity = codeList.get(0);
			prefix = baseCodeNumberEntity.getPrefix();
			num = baseCodeNumberEntity.getCurrentNum();
			if(length==null) {
				length = 7;
			}
			num++;
			baseCodeNumberEntity.setCurrentNum(num);
			baseCodeNumberService.update(baseCodeNumberEntity);
			code = prefix + StringUtils.leftPad(num+"", length,"0");
		}
		
		return code;
	}
}
